let tip = require('@/libs/tip.js');
let jdate = require('@/libs/jdate.js');
let go = require('@/libs/go.js');
import md5 from '@/libs/md5.js';

let xlog = process.env.NODE_ENV === 'development' ? console.log : () => {};

/**
 * post
 */
function vapi(apiPath, postData, handle) {
	return _post(apiPath, postData, handle, 'vapi');
}

function _post(apiPath, postData, handle, md) {
	if (!postData) postData = {};
	if (!handle) handle = {};

	let gData = getApp().globalData;

	//是否已设置了appid
	if (gData.appid) postData.appid = gData.appid;

	//还没有初始化
	if (!postData.appid) {
		setTimeout(() => {
			_post(apiPath, postData, handle, md)
		}, 300);
		return;
	}

	if (gData.onlineKey) postData.onlinekey = postData.skey = gData.onlineKey;

	if (gData.systemInfo) {
		postData.plat = 'wxapp_' + gData.appstag;
		postData.systemplat = gData.systemInfo.system;
	}

	postData.versioncode = gData.versionNum;
	postData.time = jdate.time();
	postData.sign = md5(postData.time + postData.appid + (postData.id ? postData.id : '') + (postData.onlinekey ? postData
		.onlinekey : ''));

	//
	if (!handle.fail) {
		handle.fail = (code, msg) => {
			xlog('【url:error】 :' + apiPath + ';post:', postData);
			return tip.alert(msg, 'fail');
		}
	}

	xlog('【url:start】 :' + apiPath + ';post:', postData);

	let fileType = 'image';
	let filePath = '';
	let fileName = '';

	if (postData['@file']) {
		let file = postData['@file'];
		if (file.type) fileType = file.type;
		if (file.path) filePath = file.path;
		if (file.name) fileName = file.name;

		delete postData['@file'];
	}

	let urls = {
		vapi: 'https://www.xmemc.cn/api/',
	};

	let method = 'POST';

	let url = urls[md];

	url += apiPath;

	let postFn = uni.request;
	let header = {
		'content-type': 'application/x-www-form-urlencoded'
	};

	if (filePath) {
		postFn = uni.uploadFile;
		header = null;
	}

	postFn({
		url,
		formData: postData,
		data: postData,
		method,
		dataType: 'json',
		name: fileName,
		filePath,
		fileType,
		header,
		success: function(rep) {
			xlog('【url:got】 :' + apiPath + ';post:', postData, ';data:', rep.data);

			let json = rep.data;
			if (filePath) {
				try {
					json = JSON.parse(json);
				} catch (e) {
					json = {};
				}
			}

			if (!json) json = {};
			if (handle.ever) handle.ever(json);
			if (!json.code || json.code != '200') {
				if(json.code == '201'){
					uni.showModal({
						showCancel:true,
						content:'请登录',
						confirmText:'马上登陆',
						cancelText:'下次再说',
						success: function (res) {
							if (res.confirm) {
								go.burl('account/login');
							}
						}
					}) ;
					return ; 
				}
				return handle.fail(json.code, json.msg ? json.msg : '网络错误，请重试！');
			}

			if (!json.data) json.data = {};
			if (handle.succ) handle.succ(json.data);
			return;

		},
		fail: function() {
			if (handle.ever) handle.ever();
			return handle.fail('-503', '网络错误!');
		}
	});
};


module.exports = {
	vapi,
}
